package com.topboya.linker.ui.presenter;


import com.topboya.linker.R;
import com.topboya.linker.api.ApiRetrofit;
import com.topboya.linker.model.response.CreateDocCustomerResponse;
import com.topboya.linker.model.response.CustomerByOrgIdAndNewlyCusListResopnse;
import com.topboya.linker.model.response.CustomerByOrgIdResponse;
import com.topboya.linker.model.response.DictByKeyResponse;
import com.topboya.linker.model.response.NewlyOrgListResponse;
import com.topboya.linker.model.response.OrganizationResopnse;
import com.topboya.linker.ui.base.Presenter.BasePresenter;
import com.topboya.linker.ui.base.activity.BaseActivity;
import com.topboya.linker.ui.view.CustomerView;
import com.topboya.linker.utils.LogUtils;
import com.topboya.linker.utils.UIUtils;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

public class CustomerPresenter extends BasePresenter<CustomerView> {

    private static final String TAG = "CustomerPresenter-";

    public CustomerPresenter(BaseActivity context) {
        super(context);

    }


    public void getOrgList(String pageNo,String orgName) {

        mContext.showWaitingDialog(UIUtils.getString(R.string.please_wait));
        ApiRetrofit.getInstance().getOrgList(pageNo,orgName)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(organizationResopnse -> {

                    String success = organizationResopnse.getMeta().getSuccess();
                    if (null != success && Boolean.parseBoolean(success)) {
                        ArrayList<OrganizationResopnse.DocDetailInfoList>  docDetailInfoListOrg = (ArrayList<OrganizationResopnse.DocDetailInfoList>) organizationResopnse.getData().getDocDetailInfoList();
//                        LogUtils.v(TAG + " result:" + docDetailInfoListOrg.toString());
                        getNewlyOrgList(docDetailInfoListOrg);

                    }
                }, this::getOrgError);

    }

    public void getNewlyOrgList(ArrayList<OrganizationResopnse.DocDetailInfoList> docDetailInfoList ) {

        mContext.showWaitingDialog(UIUtils.getString(R.string.please_wait));
        ApiRetrofit.getInstance().getNewlyOrgList()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(newlyOrgListResponse -> {

                    mContext.hideWaitingDialog();
                    String success = newlyOrgListResponse.getMeta().getSuccess();
                    if (null != success && Boolean.parseBoolean(success)) {
                        ArrayList<NewlyOrgListResponse.Data>  docDetailInfoListOrgNewly= (ArrayList<NewlyOrgListResponse.Data>) newlyOrgListResponse.getData();

                        getView().setCustomeData(docDetailInfoList,docDetailInfoListOrgNewly);
                        LogUtils.v(TAG + " result:" + docDetailInfoListOrgNewly.toString());

                    }
                }, this::getOrgError);

    }

    private void getOrgError(Throwable throwable) {

        LogUtils.v(throwable.getLocalizedMessage());
//        UIUtils.showToast(throwable.getLocalizedMessage());
        LogUtils.v(TAG + "getOrgError:" + throwable.getLocalizedMessage());
        mContext.hideWaitingDialog();
    }

//    获取最近拜访的对象
    public void getCustomerByOrgIdAndNewlyCusList(String orgId,boolean isSelectActivity){

        mContext.showWaitingDialog(UIUtils.getString(R.string.please_wait));
        ApiRetrofit.getInstance().getCustomerByOrgIdAndNewlyCusList(orgId)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(customerByOrgIdAndNewlyCusListResopnse -> {
                    mContext.hideWaitingDialog();
                    String success = customerByOrgIdAndNewlyCusListResopnse.getMeta().getSuccess();

                    if (null != success && Boolean.parseBoolean(success)) {

//                        getCustomerByOrgId(orgId,true);
                        List<List<CustomerByOrgIdAndNewlyCusListResopnse.CusListChild>> cusListChild;

                        List<CustomerByOrgIdAndNewlyCusListResopnse.NewlyCusList> newlyCusLists = customerByOrgIdAndNewlyCusListResopnse.getData().getNewlyCusList();
                        List<CustomerByOrgIdAndNewlyCusListResopnse.CusListChild> cusLists = customerByOrgIdAndNewlyCusListResopnse.getData().getCusList().getList();

                        cusListChild= dividerList(cusLists, (o1, o2) -> o1.getDepartment().equals(o2.getDepartment()) ? 0:-1);

                        for (int i=0; i< cusListChild.size();i++){

                            LogUtils.v(TAG + "cusListChild:"+cusListChild.get(i).toString());
                        }

                        getDictByKey("hos_department",cusListChild,isSelectActivity,newlyCusLists);



                    }

                }, this::getOrgError);


    }
    public void getCustomerByOrgId(String orgID ,boolean isSelectActivity) {

        mContext.showWaitingDialog(UIUtils.getString(R.string.please_wait));
        ApiRetrofit.getInstance().getCustomerByOrgId(orgID)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(customerbyorgidresponse -> {

                    LogUtils.v(TAG + " getCustomerByOrgId_result:" + customerbyorgidresponse.toString());
                    mContext.hideWaitingDialog();
                    String success = customerbyorgidresponse.getMeta().getSuccess();
                    if (null != success && Boolean.parseBoolean(success)) {
                        List<CustomerByOrgIdResponse.DepartmentList> departmentlist = customerbyorgidresponse.getData().getList();

                        if (isSelectActivity){
                            //分组按照科室分组
                            List<List<CustomerByOrgIdResponse.DepartmentList>> departmentgrouplist;

                            departmentgrouplist=  dividerList(departmentlist, (o1, o2) -> o1.getDepartment().equals(o2.getDepartment()) ? 0:-1);
                            for (int i=0; i< departmentgrouplist.size();i++){

                                LogUtils.v(TAG + "departmentgrouplist:"+departmentgrouplist.get(i).toString());
                            }

//                            getDictByKey("hos_department",departmentgrouplist,isSelectActivity);
                        }else {

//                            进入选择用户页面
                            getView().setDepartment(departmentlist);

                        }


                    }

                }, this::getOrgError);
    }

    public void getDictByKey(String type , List<List<CustomerByOrgIdAndNewlyCusListResopnse.CusListChild>> cusListChild,boolean isSelectActivity,List<CustomerByOrgIdAndNewlyCusListResopnse.NewlyCusList> newlyCusLists ) {

        mContext.showWaitingDialog(UIUtils.getString(R.string.please_wait));
        ApiRetrofit.getInstance().getDictByKey(type)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(dictByKeyResponse -> {
                    LogUtils.v(TAG + " result:" + dictByKeyResponse.toString());
                    mContext.hideWaitingDialog();
                    String success = dictByKeyResponse.getMeta().getSuccess();
                    List<DictByKeyResponse.Data> data = dictByKeyResponse.getData();
                    LogUtils.v(TAG + data.toString());

                    if (null != success && Boolean.parseBoolean(success)) {
                        if (isSelectActivity){
                            //科室和人员键值对存入hashmap
                            HashMap<String,List<CustomerByOrgIdAndNewlyCusListResopnse.CusListChild>> departmentgroupmap = new HashMap();
                            for (int j=0;j <cusListChild.size();j++) {
                                String department = cusListChild.get(j).get(0).getDepartment();
                                for (int i=0;i < data.size() ;i ++){

                                    if (department.equals(data.get(i).getValue())){

                                        departmentgroupmap.put(data.get(i).getLabel(),cusListChild.get(j));
                                    }
                                }
                            }
                            for(Map.Entry<String,  List<CustomerByOrgIdAndNewlyCusListResopnse.CusListChild>> entry : departmentgroupmap.entrySet()) {
                                System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
                            }
//                            orgsubAndNameListener.getresult(departmentgroupmap);
                            getView().setDepartVisitor(departmentgroupmap,newlyCusLists);

                        }else {

//                            直接查询
                              getView().setDictByKey(data);

                        }

                    }
                }, this::getOrgError);
    }

    /**
     * 创建比较器
     */
    public static <T> List<List<T>> dividerList(List<T> list,Comparator<? super T> comparator) {
        List<List<T>> lists = new ArrayList<>();

        for (int i = 0; i < list.size(); i++) {
            boolean isContain = false;
            for (int j = 0; j < lists.size(); j++) {
                if (lists.get(j).size() == 0||comparator.compare(lists.get(j).get(0),list.get(i)) == 0) {
                    lists.get(j).add(list.get(i));
                    isContain = true;
                    break;
                }
            }
            if (!isContain) {
                List<T> newList = new ArrayList<>();
                newList.add(list.get(i));
                lists.add(newList);
            }
        }
        return lists;
    }

    public interface OrgsubAndNameListener{

         void getresult(HashMap<String,List<CustomerByOrgIdResponse.DepartmentList>> departmentgroupmap);
    }


    public void createDoctorCustomer(String orgId ,String id,String cusName,String phone, String department,String posit,String workExperience) {

        mContext.showWaitingDialog(UIUtils.getString(R.string.please_wait));
        ApiRetrofit.getInstance().createDoctorCustomer(orgId ,id,cusName, phone,department,posit,workExperience)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(createdoccustomerresponse -> {
                    mContext.hideWaitingDialog();
                    LogUtils.v(TAG + " result:" + createdoccustomerresponse.toString());
                    String success = createdoccustomerresponse.getMeta().getSuccess();
                    if (null != success && Boolean.parseBoolean(success)) {
                        CreateDocCustomerResponse.Data createDocCustomerResponse = createdoccustomerresponse.getData();
                        LogUtils.v(TAG + createDocCustomerResponse.toString());
                        getView().createCustomer();
                    }
                }, this::getOrgError);
    }

}
